#include "SystemSDL_1_3.h"
#include "MainWindowSDL_1_3.h"

#include <SDL.h>

CWindowSDL_1_3* CSystemSDL_1_3_Main::m_pFocusWnd    = NULL;
SDL_Window* CSystemSDL_1_3_Main::m_hFocusWnd        = NULL;
CMainWindowSDL_1_3* CSystemSDL_1_3_Main::m_pMainWnd = NULL;
const char CSystemSDL_1_3_Main::WINDOW_PTR_NAME[]   = "window_ptr_name";    // Why is this even needed?

CSystemSDL_1_3_Main::CSystemSDL_1_3_Main( void )
{
    //ctor
}

CSystemSDL_1_3_Main::~CSystemSDL_1_3_Main( void )
{
    //dtor
}

int CSystemSDL_1_3_Main::Init( void )
{
    // initialize SDL
    if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
    {
        CSystemSDL_1_3_Helper::SetError( "ERROR: SDL_Init\n" );
        CSystemSDL_1_3_Main::Quit();

        return -1;
    }

    m_pMainWnd = new CMainWindowSDL_1_3;

    if( m_pMainWnd == NULL )
    {
        CSystemSDL_1_3_Helper::SetError( "Could not create main window\n" );
        CSystemSDL_1_3_Main::Quit();

        return -1;
    }

    m_pMainWnd->Init();

    CSystemSDL_1_3::m_isRunning = true;

    return 0;
}

int CSystemSDL_1_3_Main::ProcessEvents( void )
{
    SDL_Event ev;

    // processing events this way allows for error checking,
    // in the unlikely event that an error actually occurs
    if( SDL_PollEvent( NULL ) )
    {
        if( SDL_WaitEvent( &ev ) == 0 )
        {
            CSystemSDL_1_3_Helper::SetError( "ERROR: SDL_WaitEvent\n" );
            return -1;
        }

        //CSystemSDL_1_3_Helper::PrintEvent( ev );

        // exit if a quit event is detected.  This should only be sent by the main window.
        if( ev.type == SDL_QUIT )
        {
            CSystemSDL_1_3::m_isRunning             = false;
            return 0;
        }

        // if there are more than on window this will grab the active one.
        int window_id                               = ev.window.windowID;
        m_hFocusWnd                                 = SDL_GetWindowFromID( window_id );
        CSystemSDL_1_3_Renderer::m_hCurrentRenderer = SDL_GetRenderer( m_hFocusWnd );
        m_pFocusWnd                                 = SDL_static_cast( CWindowSDL_1_3*,
                                                                       SDL_GetWindowData( m_hFocusWnd,
                                                                       WINDOW_PTR_NAME ) );

        if( m_pFocusWnd != NULL )
            m_pFocusWnd->Process( ev );
    }

    return 0;
}

void CSystemSDL_1_3_Main::ShutDown( void )
{
    if( m_pMainWnd != NULL )
    {
        m_pMainWnd->ShutDown();

        delete m_pMainWnd;
        m_pMainWnd = NULL;
    }

    SDL_Quit();
}

void CSystemSDL_1_3_Main::Quit( void )
{
    SDL_Event ev;

    SDL_memset( &ev, 0, sizeof( SDL_Event ) );
    ev.type = SDL_QUIT;

    SDL_PushEvent( &ev );
}
